package com.smarttiger.zero.admin.task;

import com.smarttiger.zero.admin.dao.TaskDao;
import com.smarttiger.zero.admin.entity.TaskModel;
import com.smarttiger.zero.admin.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.annotation.Bean;

import java.util.List;


@Configuration
public class TaskConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    TaskDao taskDao;

    @Autowired
    private QuartzScheduler quartzScheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        List<TaskModel> taskModelList = taskDao.findAllByIsAuto("Y");
        taskModelList.forEach(task -> {
            try {
                quartzScheduler.startJob(task);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        });
        System.out.println("任务已经启动...");
    }

    @Bean
    public Scheduler scheduler() throws SchedulerException {
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }

}
